﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;


namespace ControllerClient
{
    class HexUtils
    {

        //int转字节
        public static byte[] intToBytes(int value)
        {
            byte[] src = new byte[4];
            src[0] = (byte)((value >> 24) & 0xFF);
            src[1] = (byte)((value >> 16) & 0xFF);
            src[2] = (byte)((value >> 8) & 0xFF);
            src[3] = (byte)(value & 0xFF);
            return src;
        }

        //String转字节
        public static byte[] strToHexByte(string hexString)
        {
           
            hexString = hexString.Replace(" ", "");
            if ((hexString.Length % 2) != 0) hexString = hexString.Insert(hexString.Length - 1, 0.ToString());
            byte[] returnBytes = new byte[hexString.Length / 2];
            for (int i = 0; i < returnBytes.Length; i++)
                returnBytes[i] = Convert.ToByte(hexString.Substring(i * 2, 2), 16);
            return returnBytes;
           
            
        }
        private  static char[] hexArray = "0123456789ABCDEF".ToCharArray();
        //public static String byteArrToHex(byte[] bytes)
        //{
        //    char[] hexChars = new char[bytes.Length * 2];
        //    for (int j = 0; j < bytes.Length; j++)
        //    {
        //        int v = bytes[j] & 0xFF;
        //        hexChars[j * 2] = hexArray[v >>> 4];
        //        hexChars[j * 2 + 1] = hexArray[v & 0x0F];
        //    }
        //    return new String(hexChars);
        //}
        public static string byteToHexStr(byte[] byteArray)//byte[]转HEXString
        {
            // string str = "";
            var str = new System.Text.StringBuilder();
            int start = Environment.TickCount;//计时器
           
            if (byteArray != null)
            {
              
                for (int i = 0; i < byteArray.Length; i++)
                {

                    str.Append(byteArray[i].ToString("X2"));
                }
              
            }
            string s = str.ToString();
            return s;
        }
        ////字节转string
        public static string byteToHexStr2(byte[] bytes)
        {
            int start = Environment.TickCount;//计时器
            Console.WriteLine("wait...");
            string returnStr = "";
            if (bytes != null)
            {
                for (int i = 0; i < bytes.Length; i++)
                {
                    returnStr += bytes[i].ToString("X2");
                }
            }
            Console.WriteLine("耗时==" + Math.Abs(Environment.TickCount - start));//在调试窗口可查用时
            return returnStr;
        }
        //String转16进制字符串
        public static string Str2Hex(string mStr)
        {
            return BitConverter.ToString(
            ASCIIEncoding.Default.GetBytes(mStr)).Replace("-", " ");
        }
        // 返回十六进制代表的字符串
        public static string HexToStr(string mHex) 
        {
            mHex = mHex.Replace(" ", "");
            if (mHex.Length <= 0) return "";
            byte[] vBytes = new byte[mHex.Length / 2];
            for (int i = 0; i < mHex.Length; i += 2)
                if (!byte.TryParse(mHex.Substring(i, 2), NumberStyles.HexNumber, null, out vBytes[i / 2]))
                    vBytes[i / 2] = 0;
            return ASCIIEncoding.Default.GetString(vBytes);
        } /* HexToStr */

        /**
      * 将b1和b2做异或，然后返回
      * 
      * @param b1
      * @param b2
      * @return 异或结果
      */
        public static byte[] xOr(byte[] b1, byte[] b2)
        {
            byte[] tXor = new byte[Math.Min(b1.Length, b2.Length)];
            for (int i = 0; i < tXor.Length; i++)
                tXor[i] = (byte)(b1[i] ^ b2[i]); // 异或(Xor)
            return tXor;
        }

        public static String decToHex(int dec)
        {
            String hex = "";
            while (dec != 0)
            {
                String h = Convert.ToString(dec & 0xff, 16);
                if ((h.Length & 0x01) == 1)
                    h = '0' + h;
                hex = hex + h;
                dec = dec >> 8;
            }
            return hex;
        }

        public static int ToInt(byte[] data)
        {
            if (BitConverter.IsLittleEndian)
            {
                Array.Reverse(data);
            }
            return BitConverter.ToInt32(data, 0);
        }

        public static long ToInt64(byte[] data)
        {
            if (BitConverter.IsLittleEndian)
            {
                Array.Reverse(data);
            }
            return BitConverter.ToInt64(data, 0);
        }
        public static byte[] ToBytes(uint data)
        {
            byte[] bytes = BitConverter.GetBytes(data);
            if (BitConverter.IsLittleEndian)
            {
                Array.Reverse(bytes);
            }
            return bytes;
        }

        public static byte[] ToBytes(long data)
        {
            byte[] bytes = BitConverter.GetBytes(data);
            if (BitConverter.IsLittleEndian)
            {
                Array.Reverse(bytes);
            }
            return bytes;
        }
        public static byte[] AddZero(String data)
        {
            StringBuilder sb = new StringBuilder();
            if (data.Length % 16 != 0 )
            {
                int len = ((data.Length / 16) +1) *16;
                Console.WriteLine("len" + len);
                for (int i = 0; i < len - data.Length; i++)
                {
                    sb.Append("0");

                }

            }
            data = data + sb;
            return HexUtils.strToHexByte(data);
                
        }
        public static string AddIdZero(String data)
        {
            StringBuilder sb = new StringBuilder();
            if (data.Length < 7  )
            {
                int len = ((data.Length / 7) + 1) * 7;
                Console.WriteLine("len" + len);
                for (int i = 0; i < len - data.Length; i++)
                {
                    sb.Append("0");

                }

            }
            data = sb + data;
            return data;

        }
        public static string AddLenZero(String data)
        {
            StringBuilder sb = new StringBuilder();
            if (data.Length < 28)
            {
               
                for (int i = 0; i < 28 - data.Length; i++)
                {
                    sb.Append("0");

                }

            }
            data = sb + data;
            return data;

        }
        //二进制转16进制
        public static string binStringToHexString(string bin)
        {
            string result = string.Format("{0:x}", Convert.ToInt32(bin, 2));
            return result;

        }
        //十六进制转二进制
        public static string HexStringToBinString(string hexString)
        {
            string result = string.Empty;
            foreach (char c in hexString)
            {
                int v = Convert.ToInt32(c.ToString(), 16);
                int v2 = int.Parse(Convert.ToString(v, 2));
                // 去掉格式串中的空格，即可去掉每个4位二进制数之间的空格，
                result += string.Format("{0:d4} ", v2);
            }
            return result;
        }
        public static void WriteMessage(string path, string message)
        {
            using (FileStream fs = File.Open(path, FileMode.Create, FileAccess.Write, FileShare.None))
            {

                Byte[] info = new UTF8Encoding(true).GetBytes(message);
                fs.Write(info, 0, info.Length);
            }
        }
        public static string ReadMessage(string path)
        {

            StreamReader srReadFile = new StreamReader(path);
            string strReadLine = "";
            // 读取流直至文件末尾结束
            while (!srReadFile.EndOfStream)
            {
                strReadLine = srReadFile.ReadLine(); //读取每行数据

            }
            // 关闭读取流文件
            srReadFile.Close();
            return strReadLine;
        }

        /// <summary>
        /// string 转 byte
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static byte[] Str_change_byte(string str)
        {
            byte[] Data = new byte[str.Length];
            int count = 0;
            string strSource = str.Replace("\n", "").Replace(" ", "").Replace("\t", "").Replace("\r", "");

            try
            {
                for (int i = 0; i < (strSource.Length - strSource.Length % 2) / 2; i++)//取余3运算作用是防止用户输入的字符为奇数个
                {
                    Data[count] = Convert.ToByte(strSource.Substring(i * 2, 2), 16);
                    count++;
                }
                if (strSource.Length % 2 != 0)//剩下一位单独处理
                {
                    Data[count] = Convert.ToByte(strSource.Substring(strSource.Length - 1, 1), 16);//单独处理B（0B）
                    count++;
                }
            }
            catch (Exception)
            {
                
                return null;
            }
            byte[] buf = new byte[count];
            Array.Copy(Data, 0, buf, 0, count); //复制原始数据    
            return buf;
        }
    }
}
